<?php

include 'gfw.php';
include_once 'data/config.php';
if ($qiangyinon ==1) {
include 'xinchengxu/301.php';  //xinchengxu文件夹可以改名 但是改名后一定要修改本行引用代码
}
ini_set('memory_limit', '10240M');
header('Content-Type: text/html; charset=utf-8');
$templateFolder = 'data/muban/';
$templates = glob($templateFolder . '*.html');
$template = $templates[array_rand($templates)];
$moban = file_get_contents($template);
use sqhlib\Hanzi\HanziConvert;
include_once 'data/fanti/HanziConvert.php';

function encodeValue($str) {
    $content_sz = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
    $encodedValue = '';
    foreach ($content_sz as $content) {
        $encodedValue .= '&#' . base_convert(bin2hex(mb_convert_encoding($content, 'ucs-4', 'utf-8')), 16, 10);
    }
    return $encodedValue;
}

$titlegs_list = file(__DIR__ . '/data/title.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomTitle = array_rand(array_flip($titlegs_list));
$moban = str_replace('{标题格式}', trim($randomTitle), $moban);



$miaoshugs_list = file(__DIR__ . '/data/miaoshu.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomMiaoshu = array_rand(array_flip($miaoshugs_list));

if ($miaoshuSwitch == 1) {
    $randomMiaoshu = encodeValue($randomMiaoshu);
}

$moban = str_replace('{描述格式}', trim($randomMiaoshu), $moban);


$fuzhu_list = file(__DIR__ . '/data/fuzhu.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomFuzhu = array_rand(array_flip($fuzhu_list));
if ($fzms1Switch == 1) {
    $randomFuzhu = encodeValue($randomFuzhu);
}
$moban = str_replace(['{辅助描述}', '{辅助描述1}'], trim($randomFuzhu), $moban);

$fuzhu2_list = file(__DIR__ . '/data/fzms2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomFuzhu2 = array_rand(array_flip($fuzhu2_list));
if ($fzms2Switch == 1) {
    $randomFuzhu2 = encodeValue($randomFuzhu2);
}
$moban = str_replace('{辅助描述2}', trim($randomFuzhu2), $moban);

$fuzhu3_list = file(__DIR__ . '/data/fzms3.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randomFuzhu3 = array_rand(array_flip($fuzhu3_list));
if ($fzms2Switch == 1) {
    $randomFuzhu3 = encodeValue($randomFuzhu3);
}
$moban = str_replace('{辅助描述3}', trim($randomFuzhu3), $moban);

$randomVersion = 'V.' . mt_rand(1, 9) . '.' . mt_rand(0, 19) . '.' . mt_rand(0, 19);
$moban = preg_replace('/\{当前版本\}/', $randomVersion, $moban, 10);

$moban = preg_replace_callback('/\{随机版本\}/', function($matches) {
    return 'V.' . mt_rand(1, 9) . '.' . mt_rand(0, 19) . '.' . mt_rand(0, 19);
}, $moban);


$url_list = file(__DIR__ . '/data/url.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$moban = preg_replace_callback('/\{链接\}/', function($match) use ($url_list) {
    $randomurl = array_rand(array_flip($url_list));
    return trim($randomurl);
}, $moban);

$moban = preg_replace_callback('/{随机数字(\d+)}/', function($match) {
    $length = intval($match[1]);
    return mt_rand(pow(10, ($length - 1)), pow(10, $length) - 1);
}, $moban);

$moban = preg_replace_callback('/\{固定随机字符(\d+)?\}|\{固定字符(\d+)?\}/', function($match) {
    if (!empty($match[1])) {
        $length = intval($match[1]);
        // 限制随机位数在1-20之间
        $length = max(1, min(20, $length));
    } else if (!empty($match[2])) {
        $length = intval($match[2]);
        // 限制随机位数在1-20之间
        $length = max(1, min(20, $length));
    } else {
        // 如果未指定数字，则随机生成1-20位长度
        $length = rand(1, 20);
    }
    
    // 检查是否已经生成过随机字符
    if(isset($_SESSION['randomString'])) {
        $randomString = $_SESSION['randomString'];
    } else {
        $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';//要大写就加入 ABCDEFGHIJKLMNOPQRSTUVWXYZ
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        // 保存生成的随机字符到会话中
        $_SESSION['randomString'] = $randomString;
    }
    
    return $randomString;
}, $moban);

$moban = preg_replace_callback('/\{随机字符(\d+)\}|\{字符(\d+)\}/', function($match) {
    if (!empty($match[1])) {
        $length = intval($match[1]);
    } else if (!empty($match[2])) {
        $length = intval($match[2]);
    } else {
        return $match[0];
    }
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}, $moban);


$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
$moban = preg_replace_callback('/class="/', function($matches) use ($characters) {
    $randomString = '';
    for ($i = 0; $i < 16; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return 'class="' . $randomString.' ';
}, $moban);





$moban = preg_replace_callback('/{随机字母(\d+)}/', function($match) {
    $length = intval($match[1]);

    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}, $moban);

$moban = preg_replace_callback('/{小写字母(\d+)}/', function($match) {
    $length = intval($match[1]);

    $characters = 'abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}, $moban);

$moban = preg_replace_callback('/{大写字母(\d+)}/', function($match) {
    $length = intval($match[1]);

    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}, $moban);


$biaoqing_list = file(__DIR__ . '/data/biaoqing.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$randombiaoqing = array_rand(array_flip($biaoqing_list));
$moban = str_replace('{固定表情}', trim($randombiaoqing), $moban);


$biaoqing_list = file(__DIR__ . '/data/biaoqing.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
shuffle($biaoqing_list);
$index = 0;
$moban = preg_replace_callback('/\{表情\}|\{随机表情\}/', function($matches) use ($biaoqing_list, &$index) {
    $replacement = isset($biaoqing_list[$index]) ? trim($biaoqing_list[$index]) : $matches[0];
    $index++;
    return $replacement;
}, $moban);


$img_files = glob('data/img/*.txt');
$randomImgFile = $img_files[array_rand($img_files)];
$imgLines = file($randomImgFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$moban = preg_replace_callback('/\{图片\}|\{随机图片\}/', function () use ($imgLines) {
    return trim($imgLines[array_rand($imgLines)]);
}, $moban);

$keywords_files = glob('data/keywords/*.txt');
$randomKeywordsFile = $keywords_files[array_rand($keywords_files)];
$keywordLines = file($randomKeywordsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!empty($keywordLines)) {
    $keyword = $keywordLines[array_rand($keywordLines)];
} else {
    $keyword = "";
}

$selectedKeyword = $keyword;

$keywordFiles = glob('data/keywords/*.txt');
$randomKeywordFile = $keywordFiles[array_rand($keywordFiles)];
$keywordLines = file($randomKeywordFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);


$files = glob('data/keyword/*.txt');
$file = $files[array_rand($files)];
$keyword = trim(file($file)[array_rand(file($file))]);

if ($gjc1Switch == 1) {
$moban = str_replace('{关键词1}', encodeValue($keyword), $moban);
}
$moban = str_replace('{关键词1}', $keyword, $moban);


$suijici_list = file(__DIR__ . '/data/keywords/keywords.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
shuffle($suijici_list);
$index = 0;
$moban = preg_replace_callback('/\{随机关键词2\}|\{随机关键词3\}/', function($matches) use ($suijici_list, &$index) {
    $replacement = isset($suijici_list[$index]) ? trim($suijici_list[$index]) : $matches[0];
    $index++;
    return encodeValue($replacement); // 对替换结果进行转码
}, $moban);

$juzi_files = glob('data/juzi/*.txt');
$randomJuziFile = $juzi_files[array_rand($juzi_files)];
$juziLines = file($randomJuziFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$moban = preg_replace_callback('/\{句子\}|\{随机句子\}/', function () use ($juziLines, $zmjuziSwitch) {
    $randomJuzi = trim($juziLines[array_rand($juziLines)]);
    
    if ($zmjuziSwitch == 1) {
        // 使用encodeValue转码
        $randomJuzi = encodeValue($randomJuzi);
    }
    
    return $randomJuzi;
}, $moban);

$title_files = glob('data/title/*.txt');
$randomtitleFile = $title_files[array_rand($title_files)];
$titleLines = file($randomtitleFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$moban = preg_replace_callback('/\{标题\}|\{随机标题\}/', function () use ($titleLines, $zmtitleSwitch) {
    $randomTitle = trim($titleLines[array_rand($titleLines)]);
    
    if ($zmtitleSwitch == 1) {
        // 使用encodeValue转码
        $randomTitle = encodeValue($randomTitle);
    }
    
    return $randomTitle;
}, $moban);

$reci_files = glob('data/reci/*.txt');
$randomreciFile = $reci_files[array_rand($reci_files)];
$reciLines = file($randomreciFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$moban = preg_replace_callback('/\{热词\}|\{随机热词\}/', function () use ($reciLines, $reciSwitch) {
    $randomHotWord = trim($reciLines[array_rand($reciLines)]);
    
    if ($reciSwitch == 1) {
        $randomHotWord = encodeValue($randomHotWord);
    }
    
    return $randomHotWord;
}, $moban);


$url = $_SERVER['HTTP_HOST'];
preg_match('/[\w][\w-]*\.(?:com\.cn|net\.cn|org\.cn|gov\.cn|ren|top|com|xyz|shop|mobi|kim|biz|work|store|online|wiki|video|show|world|chat|fund|guru|email|fashion|yoga|host|website|bio|green|pet|promo|VOTO|wang|sohu|net|vip|ink|red|ltd|auto|law|tech|art|love|social|cool|cfd|cx|today|company|gold|run|life|fit|space|archi|black|Lotto|pink|ski|citic|xin|club|site|info|pro|group|link|Beer|fun|design|center|team|zone|city|live|plus|pub|co|luxe|baidu|cloud|press|asia|blue|organic|poker|vote|com|net|space|pro|cyou|org|info|biz|me|mobi|name|cc|tv|co|io|in|cn|us|eu|uk|la|ws|au|jp|kr|shop|xyz|me|fun|store|ltd|pro|xin|vip|site|online|club|work|top|icu|cn|edu|net|org|gov|cc|biz|tech|info)(\/|$)/isU', $url, $match);
$zym = $match[0];
$moban = str_replace("{根域名}", $zym, $moban);
$moban = str_replace("{主域名}", $_SERVER['HTTP_HOST'], $moban);
$moban = str_replace("<title>", "<!--禁止用于违法、违规，禁止联网使用本源码，仅供本地学习--><title>", $moban);
$currentUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$moban = str_replace("{当前url}", $currentUrl, $moban);
$now = time();
$yesterday = strtotime('-1 day');
for ($i = 0; $i < 1000; $i++) {
    $randomTimestamp = mt_rand($yesterday, $now);
    $sjtime = date('Y-m-d H:i:s', $randomTimestamp);
    $moban = preg_replace('/{随机时间}|{动态时间}/', $sjtime, $moban, 1);
}
$time = date("Y-m-d H:i:s");
$time2 = date("Y年m月d日 l");
$weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
$weekdayEnglish = date("l");
$weekdayChinese = $weekdays[array_search($weekdayEnglish, $weekdays)];
$time2 = str_replace($weekdayEnglish, $weekdayChinese, $time2);
$time3 = date("Y-m-d");
$time4 = date("Y");
$time5 = date("m");
$time6 = date("d");
$time8 = time();

$moban = preg_replace([
    '/{时间}|{当前时间}/',
    '/{当前日期}/',
    '/{年月日}/',
    '/{年}/',
    '/{月}/',
    '/{日}/',
    '/{时间戳}/'
], [
    $time,
    $time2,
    $time3,
    $time4,
    $time5,
    $time6,
    $time8
], $moban);


/*新闻数据
$folderPath = 'data/news/'.date("Y-m-d").'/';
$files = glob($folderPath . '*.txt');

if (!empty($files)) {
    $randomFile = $files[array_rand($files)];
    $xwtitle = basename($randomFile, ".txt");
    $xwbody = file_get_contents($randomFile);
}

if ($zmtitleSwitch == 1) {
    $moban = str_replace('{新闻标题}', encodeValue($xwtitle), $moban);
} else {
    $moban = str_replace('{新闻标题}', $xwtitle, $moban);
}
$xwbody = str_replace('　', '', $xwbody);
$moban = str_replace('{新闻内容}', $xwbody, $moban);

*/
$NEWS_URLS = [
    "https://www.chinanews.com/china.shtml",
    "https://www.chinanews.com/scroll-news/news1.html",
    "https://www.chinanews.com/scroll-news/news2.html",
    "https://www.chinanews.com/scroll-news/news3.html"
];
$NEWS_URL = $NEWS_URLS[array_rand($NEWS_URLS)];

$html = file_get_contents($NEWS_URL);

preg_match_all('#<div class="dd_bt">.*?<a href="(.*?)".*?>(.*?)</a>.*?</div>#is', $html, $matches);

$index = array_rand($matches[0]);
$link = $matches[1][$index];
$xwtitle = $matches[2][$index];

$url = preg_match("#^https?://#i", $link) ? $link : "https://www.chinanews.com/" . ltrim($link, "/");

$xwbody_html = file_get_contents($url);

preg_match('#<div class="(left_zw|content_desc|current_img)"[^>]*>(.*?)<div class="clear">#is', $xwbody_html, $match);

$xwbody = isset($match[2]) ? $match[2] : "";
$xwbody = preg_replace('/【编辑:(.*?)】|责任编辑：【(.*?)】/', '', $xwbody);

if ($zmtitleSwitch == 1) {
    $moban = str_replace('{新闻标题}', encodeValue($xwtitle), $moban);
} else {
    $moban = str_replace('{新闻标题}', $xwtitle, $moban);
}
$xwbody = str_replace('　', '', $xwbody);
$moban = str_replace('{新闻内容}', $xwbody, $moban);

if ($zmkeywordSwitch == 1) {
    $selectedKeyword = encodeValue($keyword);
} else {
    $selectedKeyword = $keyword;
} 


$quKeyword = mb_substr($keyword, 0, 2, 'utf-8');
$moban = str_replace('{分词1}', $quKeyword, $moban);
$quKeyword2 = mb_substr($keyword, 2, 2, 'utf-8');
$moban = str_replace('{分词2}', $quKeyword2, $moban);


if ($crgjcSwitch == 1) {
    $crgjc2 = $selectedKeyword;
    $crgjc = "<strong>". $selectedKeyword . "</strong>";
    $firstPPosition = mb_strpos($xwbody, '<p>');
    if ($firstPPosition !== false) {
        $firstPTagContent = mb_substr($xwbody, $firstPPosition + 3);
        $insertPosition = $firstPPosition + 3 + 14;
        $crgjc2 = mb_convert_encoding($crgjc2, 'UTF-8');
        $xwbody = mb_substr($xwbody, 0, $insertPosition) . $crgjc2 . mb_substr($xwbody, $insertPosition);
    }
    $lastPPosition = mb_strrpos($xwbody, '<p>');
    if ($lastPPosition !== false) {
        $lastPTagContent = mb_substr($xwbody, $lastPPosition + 3);
        $insertPosition = $lastPPosition + 3 + 14;
        $crgjc = mb_convert_encoding($crgjc, 'UTF-8');
        $xwbody = mb_substr($xwbody, 0, $insertPosition) . $crgjc . mb_substr($xwbody, $insertPosition);
    }
}




$folderPath = 'data/gpt/';
$files = glob($folderPath . '*.txt');

if (!empty($files)) {
    $randomFile = $files[array_rand($files)];
    $bdtitle = basename($randomFile, ".txt");
    $bdbody = file_get_contents($randomFile);

    if ($article_switch == 2) {
        if ($titleccSwitch == 1) {
            $moban = str_replace('{关键词}', $selectedKeyword, $moban);
            $moban = preg_replace_callback('/\{随机关键词\}/', function () use ($keywordLines) {
                return trim($keywordLines[array_rand($keywordLines)]);
            }, $moban);

            $bdtitleArr = explode("\n", $bdtitle); // 将$bdtitle按行分割成数组
            $keywordLines = trim($keywordLines[array_rand($keywordLines)]); // 随机选择一个关键词

            // 获取标题长度
            $titleLength = mb_strlen($bdtitle, 'utf-8');
            // 在随机位置插入 $keywordLines
            $randomPosition = mt_rand(0, $titleLength);
            $result = mb_substr($bdtitle, 0, $randomPosition, 'utf-8') . $keywordLines . mb_substr($bdtitle, $randomPosition, null, 'utf-8');

if ($zmtitleSwitch == 1) {
        $moban = str_replace('{文章标题}', encodeValue($result), $moban);
        $moban = str_replace('{文章标题}', encodeValue($bdtitle), $moban);
        }
            $moban = str_replace('{文章标题}', $result, $moban);
            $moban = preg_replace_callback('/\{文章标题\}/', function () use ($result) {
                return $result;
            }, $moban);
        } else {
            $moban = str_replace('{文章标题}', $bdtitle, $moban);
            $moban = str_replace('{关键词}', $selectedKeyword, $moban);
            $moban = preg_replace_callback('/\{随机关键词\}/', function () use ($keywordLines) {
                return trim($keywordLines[array_rand($keywordLines)]);
            }, $moban);
        }
        
        if ($zmtitleSwitch == 1) {
        $moban = str_replace('{文章标题}', encodeValue($result), $moban);
        $moban = str_replace('{文章标题}', encodeValue($bdtitle), $moban);
        }

        $moban = str_replace('{文章内容}', $bdbody, $moban);
        $moban = str_replace('{关键词}', encodeValue($randomKeyword), $moban);
        // 多次替换{随机关键词}
        while (strpos($moban, '{随机关键词}') !== false) {
            $randomFile = $files[array_rand($files)];
            $randomKeyword2 = basename($randomFile, ".txt");
            
            if ($zmkeywordsSwitch == 1) {
            $moban = preg_replace('/{随机关键词}/', encodeValue($randomKeyword2), $moban, 1);
            }
            $moban = preg_replace('/{随机关键词}/', $randomKeyword2, $moban, 1);
        }
    } else {
        $moban = str_replace('{关键词}', $selectedKeyword, $moban);
        $moban = preg_replace_callback('/\{随机关键词\}/', function () use ($keywordLines) {
            return trim($keywordLines[array_rand($keywordLines)]);
        }, $moban);

        $titleArray = preg_split('//u', $xwtitle, -1, PREG_SPLIT_NO_EMPTY); // 将$xwtitle分割为数组
        $titleLength = count($titleArray); // 获取数组长度
        $insertPosition = mt_rand(0, $titleLength); // 随机插入位置
        array_splice($titleArray, $insertPosition, 0, $selectedKeyword); // 在指定位置插入$selectedKeyword
        $result = implode('', $titleArray); // 拼接标题字符串

        if ($zmtitleSwitch == 1) {
            $moban = str_replace('{文章标题}', encodeValue($result), $moban);
            $moban = str_replace('{文章标题}', encodeValue($xwtitle), $moban);
            $moban = str_replace('{文章内容}', $xwbody, $moban);
        } else {
            $moban = str_replace('{文章标题}', $result, $moban);
            $moban = str_replace('{文章内容}', $xwbody, $moban);
        }
    }
}



// 引入拼音转换类库以及文件操作类库
require_once __DIR__ . '/data/pinyin.php';

// 获取 data 目录下所有的 txt 文件
$dir = 'data/juzi/';
$files = scandir($dir);
$txtFiles = array_filter($files, function($file) {
    return pathinfo($file, PATHINFO_EXTENSION) === 'txt';
});

// 循环生成10个带拼音的句子
for ($i = 1; $i <= 10; $i++) {
    // 随机选取一个 txt 文件，并读取其中的一行中文
    $filename = $dir . $txtFiles[array_rand($txtFiles)];
    $line = '';
    if (($handle = fopen($filename, 'r')) !== false) {
        $randomLineNum = rand(0, count(file($filename)) - 1); // 随机选取一行
        while (($row = fgets($handle)) !== false) {
            if (--$randomLineNum < 0) {
                $line = trim($row);
                break;
            }
        }
        fclose($handle);
    }

    // 去除字符串中的空格和空字符
    $line = preg_replace('/[\s　]+/u', '', $line);

    // 将中文转换为带拼音的格式
    $pyLine = '';
    $pyLine1 = '';
    for ($j = 0; $j < mb_strlen($line); $j++) {
        $char = mb_substr($line, $j, 1);
        $pinyin = Pinyin::getPinyin($char, 'UTF-8');
        if (!empty($pinyin)) {
            $pyLine .= $pinyin;
            $pyLine1 .= $char . '(' . $pinyin . ')';
        } else {
            $pyLine .= $char;
            $pyLine1 .= $char;
        }
    }

    // 替换模板中的占位符{拼音内容}为转换后的拼音内容
    $moban = str_replace('{拼音内容}', $pyLine, $moban);
    $moban = str_replace('{拼音内容2}', $pyLine1, $moban);
}


$shuangpin_files = glob('data/shuangpin.txt');
$randomshuangpinFile = $shuangpin_files[array_rand($shuangpin_files)];
$shuangpinLines = file($randomshuangpinFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$moban = preg_replace_callback('/\{双拼\}/', function ($matches) use ($shuangpinLines, $zmshuangpinSwitch) {
    $randomshuangpin = trim($shuangpinLines[array_rand($shuangpinLines)]);
    return $randomshuangpin;
}, $moban);



//繁体功能
if ($fantiSwitch == 1) {
    // 使用 HanziConvert 类进行简繁体转换
    $moban = HanziConvert::convert($moban, true);
} else {
}

$context = stream_context_create([
    'http' => [
        'timeout' => 0.5, // 设置超时时间为500毫秒
    ],
]);
if ($xgcwitch == 1) {
$xgurl = "https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&wd=";
if ($article_switch == 2) {
    $xgurl .= urlencode($randomKeyword);
} else {
    $xgurl .= urlencode($selectedKeyword);
}
    
    
    $json_data = @file_get_contents($xgurl, false, $context);

    if ($json_data !== false) {
        $xgdata = json_decode($json_data, true);
        $jieda = "";

        if (isset($xgdata['g'])) {
            foreach ($xgdata['g'] as $i => $xgitem) {
                if ($i < 3) { // 最多显示3组内容
                    $jieda .= "<p>第" . ($i + 1) . " ".$randombiaoqing . encodeValue($xgitem['q']) . $randomHotWord . "</p>";
                }
            }
        }
        $moban = preg_replace('/(<p>)(.*?)(<\/p>)/', '${1}' . $jieda . '${2}${3}', $moban, 1);
    } else {
        $moban = preg_replace('/(<p>)(.*?)(<\/p>)/', '', $moban, 1);
    }
}

// 缓存开关为1时，生成缓存文件
if ($cacheSwitch == 1) {
    $cacheFolder = 'cache/';
    if (!file_exists($cacheFolder)) {
        mkdir($cacheFolder, 0777, true);
    }

    // 使用md5命名缓存文件
    $cacheName = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    $cacheFile = $cacheFolder . $cacheName;

    // 检查缓存文件是否存在
    if (file_exists($cacheFile)) {
        // 如果缓存文件存在，则直接读取并输出缓存内容
        echo file_get_contents($cacheFile);
        exit;
    } else {
        // 缓存文件不存在，将模板内容写入缓存文件
        file_put_contents($cacheFile, $moban);
    }
}

echo $moban;
?>